package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@Api(tags = "通用接口类")
@RequestMapping(value = "/admin/common")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /*
     * 用户上传文件接口方法
     * */
    @PostMapping(value = "/upload")
    @ApiOperation(value = "文件上传方法")
    public Result<String> upload(@RequestParam(value = "file") MultipartFile file) { // 绑定参数名，表示前端传递过来的参数名file
        log.info("文件上传:{}", file);
        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件拓展名
            assert originalFilename != null;
            String extensionName = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 使用UUID设置上传到服务器的文件名
            String randomFileName = UUID.randomUUID().toString().replace("-", "") + extensionName;
            // 设置文件访问路径
            String filePath = aliOssUtil.upload(file.getBytes(), randomFileName); // getBytes()将文件转化为字节流
            // 返回文件访问路径
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败，{}", e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED); // 返回前端文件上传失败
    }
}
